package com.ruibang.glass.quality.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.common.domain.file.FileBusiness;
import com.ruibang.glass.quality.constant.Constants;
import com.ruibang.glass.quality.domain.req.SpacerPaperReq;
import com.ruibang.glass.quality.entity.SpacerPaper;
import com.ruibang.glass.quality.feign.FileApi;
import com.ruibang.glass.quality.mapper.SpacerPaperMapper;
import com.ruibang.glass.quality.service.SpacerPaperService;
import com.ruibang.glass.quality.util.PoiUtils;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.common.model.ResultBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 来料-间隔纸 服务实现类
 * </p>
 *
 * @author songJinKang
 * @since 2024-05-21
 */
@Slf4j
@Service
public class SpacerPaperServiceImpl extends ServiceImpl<SpacerPaperMapper, SpacerPaper> implements SpacerPaperService {

    @Autowired
    private FileApi fileApi;

    @Autowired
    private RedisSingleService redisService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveInfo(SpacerPaper spacerPaper) {
        //保存
        this.save(spacerPaper);
        //保存文件
        if (CollectionUtils.isNotEmpty(spacerPaper.getFileIds())) {
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setFileIds(spacerPaper.getFileIds());
            fileBusiness.setBusinessId(spacerPaper.getId());
            fileApi.updateBusinessById(fileBusiness);
        }
    }

    @Override
    public IPage<SpacerPaper> pageQuery(SpacerPaperReq spacerPaperReq) {
        QueryWrapper<SpacerPaper> qw = new QueryWrapper<>();
        qw.lambda().like(StringUtils.isNotBlank(spacerPaperReq.getSupplierName()), SpacerPaper::getSupplierName, spacerPaperReq.getSupplierName());
        qw.lambda().like(StringUtils.isNotBlank(spacerPaperReq.getIncomingDate()), SpacerPaper::getIncomingDate, spacerPaperReq.getIncomingDate());
        return this.page(new Page<>(spacerPaperReq.getPageNo(), spacerPaperReq.getPageSize()), qw);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(SpacerPaper spacerPaper) {
        //修改
        this.updateById(spacerPaper);
        //修改文件
        if (CollectionUtils.isNotEmpty(spacerPaper.getFileIds())) {
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setFileIds(spacerPaper.getFileIds());
            fileBusiness.setBusinessId(spacerPaper.getId());
            fileApi.updateBusinessById(fileBusiness);
        }
    }

    @Override
    public SpacerPaper importExcel(MultipartFile file) {
        if (file != null) {
            //上传文件
            ResultBody<String> resultBody = fileApi.uploadFile(file);
            SpacerPaper spacerPaper = new SpacerPaper();
            if (resultBody != null && StringUtils.isNotBlank(resultBody.getData())) {
                spacerPaper.setUpLoadFileId(resultBody.getData());
            }
            // 创建一个 XSSFWorkbook 对象
            Workbook workbook = null;
            try {
                workbook = new XSSFWorkbook(file.getInputStream());
            } catch (Exception e) {
                //如果不是excel直接上传文件返回
                return spacerPaper;
            }
            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
            //供应商
            String supplierName = PoiUtils.getValue(sheet, 2, 0);
            spacerPaper.setSupplierName(supplierName);
            //来料日期
            String incTime = PoiUtils.getValue(sheet, 2, 3);
            spacerPaper.setIncomingDate(incTime);
            //检验日期
            String checkTime = PoiUtils.getValue(sheet, 2, 4);
            spacerPaper.setCheckTime(checkTime);
            //检验人
            String checkUserName = PoiUtils.getValue(sheet, 2, 8);
            if (StringUtils.isNotBlank(checkUserName)) {
                Map<Object, Object> userMap = redisService.hmget(RedisKey.USER_GROUP_TYPE);
                if (!userMap.isEmpty()) {
                    Map<String, String> userNameMap = new HashMap<>(16);
                    userMap.forEach((k, v) -> {
                        if (v != null && StringUtils.isNotBlank(v.toString())) {
                            userNameMap.put(v.toString(), k.toString());
                        }
                    });
                    spacerPaper.setCheckUserId(userNameMap.get(checkUserName));
                }
                spacerPaper.setCheckUserName(checkUserName);
            }
            //判定结果
            List<String> determineList = new ArrayList<>();
            for (int i = 7; i < 15; i++) {
                determineList.add(PoiUtils.getValue(sheet, i, 9));
            }
            String determine = determineList.contains(Constants.NG) ? Constants.ONE_STR : Constants.ZERO_STR;
            spacerPaper.setDetermine(determine);
            return spacerPaper;
        }
        return null;
    }


}
